package com.example.demo.controller;

import com.example.demo.pojo.Emp;
import com.example.demo.pojo.Result;
import com.example.demo.service.EmpService;
import com.example.demo.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class LoginController {

    @Autowired
    EmpService empService;


    @PostMapping("/login")
    public Result login(@RequestBody Emp emp){
        log.info("进行登录校验:{}",emp);
        Emp emp1 = empService.login(emp);

        //登陆成功，生产令牌，下发令牌
        if(emp1 != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", emp1.getId());
            claims.put("username", emp1.getUsername());
            claims.put("name", emp1.getName());
            String jwt = JwtUtils.generateJwt(claims);
            log.info(jwt);
            log.info(String.valueOf(JwtUtils.parseJWT(jwt)));
            return Result.success(jwt);
        }
        return Result.error("用户名或密码错误");
    }


}
